<template>
  <el-select 
    v-model="province" 
    placeholder="请选择省份" 
    filterable
    clearable
  >
    <el-option 
      v-for="(item, index) in selectProvince"
      :key="index"
      :label="item.name"
      :value="item.code"
    />
  </el-select>
  <el-select 
    v-model="city" 
    placeholder="请选择城市" 
    filterable
    clearable
    :disabled="!province"
    style="margin: 0 10px"
  >
    <el-option 
      v-for="(item, index) in selectCity"
      :key="index"
      :label="item.name"
      :value="item.code"
    />
  </el-select>
  <el-select
    v-model="area" 
    placeholder="请选择区域" 
    filterable
    clearable
    :disabled="!province || !city"
    style="margin: 0 10px"
  >
    <el-option 
      v-for="(item, index) in selectArea"
      :key="index"
      :label="item.name"
      :value="item.code"
    />
  </el-select>
</template>

<script lang='ts' setup>
import { ref, computed, watch } from 'vue'
import allArea from './lib/pca-code.json'

export interface AreaItem {
  name: string,
  code: string,
  children?: AreaItem[]
}
export interface Data {
  name: string,
  code: string,
}

// 给父组件传参
let emit = defineEmits(['change'])

// 省市区的值
let province = ref<string>('')
let city = ref<string>('')
let area = ref<string>('')

// 省市区下拉列表
let selectProvince = ref(allArea)
let selectCity = ref<AreaItem[]>([])
let selectArea = ref<AreaItem[]>([])

// 监听省份变化
watch(
  () => province.value,
  (val) => {
    city.value = ''
    area.value = ''
    if(!val) {
      selectCity.value = []
    } else {
      selectCity.value = selectProvince.value.find(item => item.code === province.value)!.children
    }
  }
)
// 监听城市变化
watch(
  () => city.value,
  (val) => {
    area.value = ''
    if(!val) {
      selectArea.value = []
    } else {
      selectArea.value = selectCity.value.find(item => item.code === city.value)!.children!
    }
  }
)

// 监听区域变化
watch(
  () => area.value,
  (val) => {
    let provinceData: Data = {
      code: province.value,
      name: selectProvince.value.find(item => item.code === province.value)?.name!
    }
    let cityData: Data = {
      code: city.value,
      name: selectCity.value.find(item => item.code === city.value)?.name!
    }
    let areaData: Data = {
      code: val,
      name: selectArea.value.find(item => item.code === val)?.name!
    }
    emit('change', {
      province: provinceData,
      city: cityData,
      area: areaData
    })
  }
)

</script>

<style lang='scss' scoped>

</style>